﻿using System;
using System.ComponentModel;
using System.Globalization;
using System.Resources;
using System.Threading;
using System.Windows;

namespace Foundation.Markup
{
    public class Localizing : MarkupExtension
    {
        public static readonly LocalizingManager Manager = new LocalizingManager();

        public Localizing()
        {
            Source = Manager;
            Path = new PropertyPath("Source");
        }

        public string Key { get; set; }

        public override string ToString()
        {
            return Convert(Manager.Source, null, Key, Thread.CurrentThread.CurrentCulture) as string ??
                   string.Empty;
        }

        public override object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var key = Key;
            var resourceManager = value as ResourceManager;
            if (resourceManager == null || string.IsNullOrEmpty(key)) return ":" + key + ":";
            var localizedValue = resourceManager.GetString(key);
            return localizedValue ?? ":" + key + ":";
        }
    }

    public class LocalizingManager : INotifyPropertyChanged
    {
        private ResourceManager _source;
        public ResourceManager Source
        {
            get { return _source; }
            set
            {
                _source = value;
                PropertyChanged(this, new PropertyChangedEventArgs("Source"));
            }
        }

        public event PropertyChangedEventHandler PropertyChanged = (sender, args) => { };
    }
}
